package com.dify.tool.controller;


import com.dify.tool.api.dto.TestDTO;
import com.dify.tool.api.vo.TestVO;
import com.dify.tool.common.model.DefaultResponse;
import com.dify.tool.common.utils.ElasticsearchUtil;
import com.dify.tool.service.ITestService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 代码生成业务表 前端控制器
 * </p>
 *
 * @author shl
 * @since 2024-06-20
 */
@Slf4j
@RestController
@RequestMapping("/test")
@Tag(description = "test", name = "测试项目")
public class TestProjectController {

    @Autowired
    private ITestService testService;

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;

    /**
     * 测试查询接口
     */
    @GetMapping("/test/query")
    @Operation(description = "测试查询接口")
    public DefaultResponse test(HttpServletRequest request) {
        System.out.println("测试请求体：" + request.getAttribute("user_type"));
        TestVO testVO = testService.test();
        return DefaultResponse.success(testVO);
    }

    @GetMapping("/es/createIndex")
    public String createIndex() throws IOException {
        elasticsearchUtil.createIndex("test");
        return "成功";
    }

    @GetMapping("/es/updateDoc")
    public String updateDoc() throws IOException {
        TestDTO testDTO = new TestDTO();
        testDTO.setName("张三").setAge(28).setMyJob("测试工程师");
        elasticsearchUtil.createDocument("test", testDTO);
        return "成功";
    }

    @GetMapping("/es/search")
    public List<TestDTO> search() throws IOException {
        ElasticsearchUtil.SearchResult<TestDTO> result = elasticsearchUtil.search(
                "test",
                TestDTO.class,
                s -> s.query(q -> q
                        .match(m -> m
                                .field("name")
                                .query("张三")
                        )
                )
        );
        return result.results();
    }

    /**
     * 测试新增接口
     */
    @PostMapping("/test/add")
    @Operation(description = "测试新增接口")
    public DefaultResponse testAdd(@RequestBody TestDTO testDTO) {
        testService.add(testDTO);
        return DefaultResponse.success();
    }

    /**
     * 测试分页查询接口
     */
    @PostMapping("/test/query/page")
    @Operation(description = "测试分页查询接口")
    public DefaultResponse testPage(@RequestBody @Validated TestDTO testDTO) {
        return DefaultResponse.success(testService.testPage(testDTO));
    }

    @PostMapping("/generateDocx")
    @Operation(description = "测试请假单")
    public byte[] generateDocx(@RequestBody Map<String, String> params) throws Exception {
        // 1. 加载模板文件
        Resource resource = new ClassPathResource("holiday.docx");
        try (InputStream is = resource.getInputStream();
             XWPFDocument doc = new XWPFDocument(is);
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            // 处理所有表格
            for (XWPFTable table : doc.getTables()) {
                processTable(table, params);
            }

            // 返回文件字节流
            doc.write(out);
            return out.toByteArray();
        }
    }

    /**
     * 处理单个表格
     */
    private void processTable(XWPFTable table, Map<String, String> data) {
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                // 处理单元格中的段落
                for (XWPFParagraph paragraph : cell.getParagraphs()) {
                    replacePlaceholdersInParagraph(paragraph, data);
                }
            }
        }
    }

    /**
     * 替换段落中的占位符
     */
    private void replacePlaceholdersInParagraph(XWPFParagraph paragraph, Map<String, String> data) {
        String text = paragraph.getText();
        if (text == null || text.isEmpty()) {
            return;
        }

        // 检查并替换所有占位符
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String placeholder = "${" + entry.getKey() + "}";
            if (text.contains(placeholder)) {
                // 清空原有内容
                for (XWPFRun run : paragraph.getRuns()) {
                    run.setText("", 0);
                }
                // 添加新内容
                XWPFRun run = paragraph.createRun();
                run.setText(entry.getValue());
                run.setFontFamily("宋体"); // 确保中文显示
                break; // 每个段落只处理一次替换
            }
        }
    }
}
